<template>
  <div class="health-statistics">
    <el-container>
      <el-header class="statistics-header">
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="goBack" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>
              返回工作台
            </el-button>
            <h2>健康数据统计</h2>
          </div>
          <div class="header-right">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
              class="date-picker"
            />
            <el-button type="primary" @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </el-header>

      <el-main class="statistics-main">
        <!-- 统计概览卡片 -->
        <el-row :gutter="20" class="overview-cards">
          <el-col :span="6">
            <el-card class="overview-card" shadow="hover">
              <div class="card-content">
                <div class="card-icon total-patients">
                  <el-icon><User /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-number">{{ statistics.totalPatients }}</div>
                  <div class="card-label">总患者数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card" shadow="hover">
              <div class="card-content">
                <div class="card-icon health-records">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-number">{{ statistics.totalRecords }}</div>
                  <div class="card-label">健康档案</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card" shadow="hover">
              <div class="card-content">
                <div class="card-icon avg-bmi">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-number">{{ statistics.avgBMI }}</div>
                  <div class="card-label">平均BMI</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card" shadow="hover">
              <div class="card-content">
                <div class="card-icon avg-bs">
                  <el-icon><Monitor /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-number">{{ statistics.avgBloodPressure }}</div>
                  <div class="card-label">平均血糖</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="charts-section">
          <!-- BMI分布图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">
                  <span class="chart-title">
                    <el-icon><PieChart /></el-icon>
                    体重分布统计
                  </span>
                </div>
              </template>
              <div ref="bmiChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <!-- 血糖分布图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">
                  <span class="chart-title">
                    <el-icon><TrendCharts /></el-icon>
                    血糖分布分析
                  </span>
                </div>
              </template>
              <div ref="bloodSugarChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="charts-section">
          <!-- 年龄分布图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">
                  <span class="chart-title">
                    <el-icon><Histogram /></el-icon>
                    年龄分布统计
                  </span>
                </div>
              </template>
              <div ref="ageChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <!-- 健康状况分布图 -->
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="chart-header">
                  <span class="chart-title">
                    <el-icon><DataAnalysis /></el-icon>
                    健康状况分布
                  </span>
                </div>
              </template>
              <div ref="developmentChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 详细数据表格 -->
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="table-header">
              <span class="table-title">
                <el-icon><List /></el-icon>
                患者健康数据详情
              </span>
              <div class="table-actions">
                <el-button type="primary" size="small" @click="exportData">
                  <el-icon><Download /></el-icon>
                  导出数据
                </el-button>
              </div>
            </div>
          </template>
          <el-table
            :data="patientData"
            v-loading="loading"
            stripe
            border
            style="width: 100%"
            :default-sort="{ prop: 'createdAt', order: 'descending' }"
          >
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="gender" label="性别" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.gender === 1 ? 'primary' : 'success'">
                  {{ scope.row.gender === 1 ? '男' : '女' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="height" label="身高(cm)" width="100">
              <template #default="scope">
                {{ scope.row.height || '未测量' }}
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="体重(kg)" width="100">
              <template #default="scope">
                {{ scope.row.weight || '未测量' }}
              </template>
            </el-table-column>
            <el-table-column prop="bmi" label="BMI" width="80">
              <template #default="scope">
                <el-tag :type="getBMIType(calculateBMI(scope.row.height, scope.row.weight))">
                  {{ calculateBMI(scope.row.height, scope.row.weight) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="systolicPressure" label="收缩压" width="100">
              <template #default="scope">
                {{ getSystolicPressure(scope.row.bloodPressure) }}
              </template>
            </el-table-column>
            <el-table-column prop="diastolicPressure" label="舒张压" width="100">
              <template #default="scope">
                {{ getDiastolicPressure(scope.row.bloodPressure) }}
              </template>
            </el-table-column>
            <el-table-column prop="heartRate" label="心率" width="80">
              <template #default="scope">
                {{ scope.row.bloodOxygen || '未测量' }}
              </template>
            </el-table-column>
            <el-table-column prop="bloodSugar" label="血糖" width="80">
              <template #default="scope">
                {{ scope.row.bloodSugar || '未测量' }}
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="记录时间" width="180" sortable>
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Refresh,
  User,
  Document,
  TrendCharts,
  Monitor,
  PieChart,
  Histogram,
  DataAnalysis,
  List,
  Download
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getHealthStatistics, getPatientHealthData } from '../api/doctor'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 统计数据
const statistics = reactive({
  totalPatients: 0,
  totalRecords: 0,
  avgBMI: 0,
  avgBloodPressure: 0,
  genderDistribution: [],
  ageDistribution: [],
  heightDistribution: [],
  weightDistribution: [],
  bloodSugarDistribution: [],
  healthStatusDistribution: [],
  bloodOxygenDistribution: [],
  visionDistribution: [],
  allergyStatistics: [],
  medicalHistoryStatistics: [],
  measuredPatients: 0,
  dataCompleteness: {}
})

// 患者数据
const patientData = ref([])

// 图表DOM引用
const bmiChartRef = ref(null)
const bloodSugarChartRef = ref(null)
const ageChartRef = ref(null)
const developmentChartRef = ref(null)

// 图表实例
let bmiChartInstance = null
let bloodSugarChartInstance = null
let ageChartInstance = null
let developmentChartInstance = null

// 获取健康统计数据
const fetchHealthStatistics = async () => {
  try {
    loading.value = true
    const params = {
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }
    
    const response = await getHealthStatistics(params)
    if (response.code === 200) {
      const data = response.data
      // 更新统计数据
      statistics.totalPatients = data.totalPatients || 0
      statistics.totalRecords = data.totalPatients || 0 // 使用总患者数作为健康档案数
      statistics.measuredPatients = data.measuredPatients || 0
      statistics.dataCompleteness = data.dataCompleteness || {}
      
      // 更新分布数据
      statistics.genderDistribution = data.genderDistribution || []
      statistics.ageDistribution = data.ageDistribution || []
      statistics.heightDistribution = data.heightDistribution || []
      statistics.weightDistribution = data.weightDistribution || []
      statistics.bloodSugarDistribution = data.bloodSugarDistribution || []
      statistics.healthStatusDistribution = data.healthStatusDistribution || []
      statistics.bloodOxygenDistribution = data.bloodOxygenDistribution || []
      statistics.visionDistribution = data.visionDistribution || []
      statistics.allergyStatistics = data.allergyStatistics || []
      statistics.medicalHistoryStatistics = data.medicalHistoryStatistics || []
      
      // 计算平均BMI和血糖（这里需要根据实际数据计算）
      statistics.avgBMI = calculateAverageBMI(data.weightDistribution, data.heightDistribution)
      statistics.avgBloodPressure = calculateAverageBloodSugar(data.bloodSugarDistribution)
      
      // 延迟更新图表，确保数据已经更新
      await nextTick()
      updateCharts()
    } else {
      ElMessage.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取健康统计数据失败:', error)
    ElMessage.error('获取统计数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 计算平均BMI
const calculateAverageBMI = (weightDistribution, heightDistribution) => {
  // 这里简化处理，实际应该根据具体的身高体重数据计算
  // 暂时返回一个示例值
  return 22.5
}

// 计算平均血糖
const calculateAverageBloodSugar = (bloodSugarDistribution) => {
  // 这里简化处理，实际应该根据具体的血糖数据计算
  // 暂时返回一个示例值
  return '5.5'
}

// 根据患者数据计算分布统计
const calculateDistributionFromPatientData = (patients) => {
  console.log('开始计算分布统计，患者数据:', patients)
  
  // 计算血糖分布
  const bloodSugarStats = {}
  const healthStatusStats = {}
  
  if (patients && patients.length > 0) {
    patients.forEach(patient => {
      // 血糖分布统计
      if (patient.bloodSugar) {
        const bloodSugar = parseFloat(patient.bloodSugar)
        if (!isNaN(bloodSugar)) {
          let category = '正常'
          if (bloodSugar < 3.9) {
            category = '偏低'
          } else if (bloodSugar > 6.1) {
            category = '偏高'
          }
          bloodSugarStats[category] = (bloodSugarStats[category] || 0) + 1
        }
      }
      
      // 健康状况分布统计
      if (patient.development) {
        const healthStatus = patient.development
        healthStatusStats[healthStatus] = (healthStatusStats[healthStatus] || 0) + 1
      }
    })
  }
  
  // 转换为数组格式，如果没有数据则使用默认值
  statistics.bloodSugarDistribution = Object.keys(bloodSugarStats).length > 0 
    ? Object.entries(bloodSugarStats).map(([name, value]) => ({ name, value }))
    : [{ name: '暂无数据', value: 0 }]
  
  statistics.healthStatusDistribution = Object.keys(healthStatusStats).length > 0
    ? Object.entries(healthStatusStats).map(([name, value]) => ({ name, value }))
    : [{ name: '暂无数据', value: 0 }]
  
  console.log('血糖分布统计:', statistics.bloodSugarDistribution)
  console.log('健康状况分布统计:', statistics.healthStatusDistribution)
  
  // 使用 nextTick 确保 DOM 更新后再更新图表
  nextTick(() => {
    updateCharts()
  })
}

// 计算BMI
const calculateBMI = (height, weight) => {
  if (!height || !weight || height === '未测量' || weight === '未测量') {
    return '未测量'
  }
  
  const h = parseFloat(height)
  const w = parseFloat(weight)
  
  if (isNaN(h) || isNaN(w) || h <= 0 || w <= 0) {
    return '未测量'
  }
  
  const bmi = w / Math.pow(h / 100, 2)
  return bmi.toFixed(1)
}

// 获取收缩压
const getSystolicPressure = (bloodPressure) => {
  if (!bloodPressure || bloodPressure === '未测量') {
    return '未测量'
  }
  
  const parts = bloodPressure.split('/')
  return parts[0] || '未测量'
}

// 获取舒张压
const getDiastolicPressure = (bloodPressure) => {
  if (!bloodPressure || bloodPressure === '未测量') {
    return '未测量'
  }
  
  const parts = bloodPressure.split('/')
  return parts[1] || '未测量'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未记录'
  
  try {
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

// 更新所有图表
const updateCharts = () => {
  console.log('开始更新图表')
  
  if (bmiChartInstance) {
    console.log('更新BMI图表')
    initBMIChart()
  }
  
  if (bloodSugarChartInstance) {
    console.log('更新血糖分布图表')
    initBloodSugarChart()
  }
  
  if (ageChartInstance) {
    console.log('更新年龄分布图表')
    initAgeChart()
  }
  
  if (developmentChartInstance) {
    console.log('更新健康状况分布图表')
    initDevelopmentChart()
  }
  
  console.log('图表更新完成')
}

// 获取患者健康数据
const fetchPatientData = async () => {
  try {
    loading.value = true
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }
    
    console.log('获取患者数据参数:', params)
    const response = await getPatientHealthData(params)
    console.log('患者数据响应:', response)
    
    if (response.code === 200) {
      const records = response.data.records || []
      patientData.value = records
      total.value = response.data.total || 0
      
      console.log('设置患者数据:', records)
      
      // 根据实际患者数据计算分布统计
      calculateDistributionFromPatientData(records)
    } else {
      ElMessage.error(response.message || '获取患者数据失败')
      // 即使获取失败也要重置分布统计
      calculateDistributionFromPatientData([])
    }
  } catch (error) {
    console.error('获取患者数据失败:', error)
    ElMessage.error('获取患者数据失败，请检查网络连接')
    // 出错时也要重置分布统计
    calculateDistributionFromPatientData([])
  } finally {
    loading.value = false
  }
}

// 初始化BMI分布图
const initBMIChart = () => {
  if (!bmiChartInstance) return
  
  // 使用实际的体重分布数据
  const weightData = statistics.weightDistribution.map(item => ({
    value: item.value,
    name: item.name,
    itemStyle: { 
      color: getWeightColor(item.name)
    }
  }))
  
  const option = {
    title: {
      text: '体重分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    },
    series: [
      {
        name: '体重分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: weightData.length > 0 ? weightData : [
          { value: 0, name: '暂无数据', itemStyle: { color: '#ccc' } }
        ]
      }
    ]
  }
  
  bmiChartInstance.setOption(option)
}

// 获取体重分布颜色
const getWeightColor = (name) => {
  const colors = {
    '50kg以下': '#5470c6',
    '50-60kg': '#91cc75',
    '61-70kg': '#fac858',
    '71-80kg': '#ee6666',
    '80kg以上': '#ff6b6b',
    '未测量': '#ccc'
  }
  return colors[name] || '#999'
}

// 初始化血糖分布图
const initBloodSugarChart = () => {
  if (!bloodSugarChartInstance) return
  
  // 使用实际的血糖分布数据
  const bloodSugarData = statistics.bloodSugarDistribution.map(item => ({
    value: item.value,
    name: item.name,
    itemStyle: { 
      color: getBloodSugarColor(item.name)
    }
  }))
  
  // 计算总数用于百分比显示
  const total = bloodSugarData.reduce((sum, item) => sum + item.value, 0)
  
  const option = {
    title: {
      text: '血糖分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0
        return `${params.name}<br/>人数: ${params.value}<br/>占比: ${percentage}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      formatter: function(name) {
        const item = bloodSugarData.find(d => d.name === name)
        if (item && total > 0) {
          const percentage = ((item.value / total) * 100).toFixed(1)
          return `${name} (${percentage}%)`
        }
        return name
      }
    },
    series: [
      {
        name: '血糖分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: function(params) {
            const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0
            return `${params.name}\n${params.value}人 (${percentage}%)`
          },
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: bloodSugarData.length > 0 ? bloodSugarData : [
          { value: 0, name: '暂无数据', itemStyle: { color: '#ccc' } }
        ]
      }
    ]
  }
  
  bloodSugarChartInstance.setOption(option)
}

// 获取血糖分布颜色
const getBloodSugarColor = (name) => {
  const colors = {
    '正常': '#91cc75',
    '偏高': '#ee6666',
    '偏低': '#5470c6',
    '未测量': '#ccc',
    '其他': '#999'
  }
  return colors[name] || '#999'
}

// 初始化年龄分布图
const initAgeChart = () => {
  if (!ageChartInstance) return
  
  // 使用实际的年龄分布数据
  const ageData = statistics.ageDistribution
  const categories = ageData.map(item => item.name)
  const values = ageData.map(item => item.value)
  
  const option = {
    title: {
      text: '年龄分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories.length > 0 ? categories : ['暂无数据']
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: values.length > 0 ? values : [0],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  ageChartInstance.setOption(option)
}

// 初始化健康状况分布图
const initDevelopmentChart = () => {
  if (!developmentChartInstance) return
  
  // 使用健康状况分布数据
  const developmentData = statistics.healthStatusDistribution
  const categories = developmentData.map(item => item.name)
  const values = developmentData.map(item => item.value)
  
  // 计算总数用于百分比显示
  const total = values.reduce((sum, value) => sum + value, 0)
  
  const option = {
    title: {
      text: '健康状况分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const data = params[0]
        const percentage = total > 0 ? ((data.value / total) * 100).toFixed(1) : 0
        return `${data.name}<br/>人数: ${data.value}<br/>占比: ${percentage}%`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories.length > 0 ? categories : ['暂无数据']
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: values.length > 0 ? values.map((value, index) => ({
          value: value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#f093fb' },
              { offset: 0.5, color: '#f5576c' },
              { offset: 1, color: '#c44569' }
            ])
          }
        })) : [0],
        label: {
          show: true,
          position: 'top',
          formatter: function(params) {
            const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0
            return `${params.value}人\n(${percentage}%)`
          },
          fontSize: 12
        }
      }
    ]
  }
  
  developmentChartInstance.setOption(option)
}

// 初始化所有图表容器
const initCharts = async () => {
  await nextTick()
  
  // 使用ref获取DOM元素，只初始化图表容器，不设置数据
  if (bmiChartRef.value) {
    bmiChartInstance = echarts.init(bmiChartRef.value)
  }
  
  if (bloodSugarChartRef.value) {
    bloodSugarChartInstance = echarts.init(bloodSugarChartRef.value)
  }
  
  if (ageChartRef.value) {
    ageChartInstance = echarts.init(ageChartRef.value)
  }
  
  if (developmentChartRef.value) {
    developmentChartInstance = echarts.init(developmentChartRef.value)
  }
  
  console.log('图表容器初始化完成')
}

// 获取BMI类型标签
const getBMIType = (bmi) => {
  if (bmi < 18.5) return 'info'
  if (bmi < 24) return 'success'
  if (bmi < 28) return 'warning'
  return 'danger'
}

// 处理日期变化
const handleDateChange = () => {
  fetchHealthStatistics()
  fetchPatientData()
}

// 刷新数据
const refreshData = () => {
  fetchHealthStatistics()
  fetchPatientData()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPatientData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPatientData()
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 返回工作台
const goBack = () => {
  router.push('/doctor-dashboard')
}

// 组件挂载
onMounted(async () => {
  // 先初始化图表容器
  await initCharts()
  
  // 然后获取数据，数据获取完成后会自动更新图表
  await fetchHealthStatistics()
  await fetchPatientData()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (bmiChartInstance) bmiChartInstance.dispose()
  if (bloodSugarChartInstance) bloodSugarChartInstance.dispose()
  if (ageChartInstance) ageChartInstance.dispose()
  if (developmentChartInstance) developmentChartInstance.dispose()
})
</script>

<style scoped>
.health-statistics {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed;
}

.statistics-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.date-picker {
  width: 300px;
}

.statistics-main {
  padding: 20px;
}

.overview-cards {
  margin-bottom: 30px;
}

.overview-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.card-icon.total-patients {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.card-icon.health-records {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.card-icon.avg-bmi {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.card-icon.avg-bs {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.card-info {
  flex: 1;
}

.card-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-label {
  color: #606266;
  font-size: 14px;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.table-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
    padding: 15px;
  }
  
  .header-right {
    flex-direction: column;
    width: 100%;
  }
  
  .date-picker {
    width: 100%;
  }
  
  .overview-cards .el-col {
    margin-bottom: 15px;
  }
  
  .charts-section .el-col {
    margin-bottom: 20px;
  }
}
</style>
